// 此页面已不再使用
import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Message, Select, Tab, Button } from '@teamix/ui';
import { ENUM } from 'utils/constants.js';
import exceed from 'utils/apimap';
import { navigateHref } from 'utils/router';
import './index.scss';
import intl from '../../locale';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const visibility_levels = [
  {
    value: ENUM.visibility_level.PRIVATE,
    label: intl.get({
      id: 'code-assets.src.utils.locale.PrivateOnlyCodeLibraryMembers',
      defaultMessage: '私有：仅代码库成员可以访问',
    }),
  },

  {
    value: ENUM.visibility_level.INTERNAL,
    label: intl.get({
      id: 'code-assets.src.utils.locale.PublicAllLogonUsersCan',
      defaultMessage: '公开：所有登录用户都可以访问',
    }),
  },

  {
    value: ENUM.visibility_level.PUBLIC,
    label: intl.get({
      id: 'code-assets.src.utils.locale.PublicNoLogonIsRequired',
      defaultMessage: '公开（无需登录）：无需登录即可访问。不符合安全要求，请尽快修改',
    }),
  },
];

export default class SettingModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    defaultActiveTab: PropTypes.string,
    defaultSettingType: PropTypes.string,
    defaultNamespaceId: PropTypes.number,
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    defaultActiveTab: '',
    defaultSettingType: 'basic',
    defaultNamespaceId: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isModalOpen: false,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    if (!this.props.trigger && this.props.defaultNamespaceId) {
      this.getSingleGroup(this.props.defaultNamespaceId);
    }
  }

  getSingleGroup = (id) => {
    exceed
      .fetch({
        api: 'groups.single',
        params: {
          id,
        },
      })
      .then((result) => {
        this.field.setValues({
          path: result.path,
          description: result.description,
          visibility_level: result.visibility_level,
        });
      });
  };

  showModal = () => {
    const { defaultNamespaceId, defaultSettingType } = this.props;
    this.setState({
      isModalOpen: true,
    });

    if (!defaultNamespaceId) {
      return;
    }
    if (defaultSettingType === 'basic') {
      this.getSingleGroup(defaultNamespaceId);
    }
  };

  pathValidator = (rule, value, callback) => {
    if (!value || /^[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,}$/.test(value)) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.src.utils.locale.ItCanOnlyContainLetters',
          defaultMessage: "只能包含字母和数字、 '_'、 '.'和'-'，且只能以字母、数字或'_'开头",
        }),
      );
    }
  };

  namespaceValidator = (rule, value, callback) => {
    if (!value) {
      callback([
        new Error(
          intl.get({
            id: 'code-assets.src.utils.locale.Select',
            defaultMessage: '请选择',
          }),
        ),
      ]);
    } else {
      callback();
    }
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  handleOk = () => {
    this.field.validate((errors) => {
      if (!errors) {
        if (this.state.submitting) {
          return;
        }
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        formData.name = formData.path;
        this.formSubmit(formData, () => {
          this.setState({ submitting: false });
        });
      }
    });
  };

  formSubmit = (formData, cb) => {
    exceed
      .fetch({
        api: 'groups.update',
        params: {
          id: this.props.defaultNamespaceId,
        },

        data: formData,
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.updateSettingModal.Success',
            defaultMessage: '成功',
          }),
        });

        this.setState({
          isModalOpen: false,
        });

        this.props.closeModal(result);
        cb && cb();
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };

  remove = () => {
    const { defaultNamespaceId } = this.props;
    if (!defaultNamespaceId) {
      return;
    }

    this.setState(
      {
        isRemoveing: true,
      },

      () => {
        exceed
          .forceFetch({
            api: 'groups.remove',
            params: {
              id: defaultNamespaceId,
            },
          })
          .then(() => {
            this.setState({
              isRemoveing: false,
              isModalOpen: false,
            });

            Message.success({
              title: intl.get({
                id: 'code-assets.components.updateSettingModal.Success',
                defaultMessage: '成功',
              }),
            });

            navigateHref('/');
          });
      },
    );
  };

  renderBasicSetting = () => {
    const { init } = this.field;
    return (
      <div className="setting-modal-tab-content">
        <Form
          {...formItemLayout}
          field={this.field}
          labelAlign="top"
          className="setting-form-wrapper"
        >
          <FormItem
            label={intl.get({
              id: 'code-assets.components.updateSettingModal.GroupName',
              defaultMessage: '分组名称',
            })}
          >
            <Input
              placeholder={intl.get({
                id: 'code-assets.src.utils.locale.EnterAName',
                defaultMessage: '请输入名称',
              })}
              {...init('path', {
                rules: [
                  {
                    required: true,
                    message: intl.get({
                      id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                      defaultMessage: '该项为必填项',
                    }),
                  },
                ],
              })}
            />
          </FormItem>
          <FormItem
            label={intl.get({
              id: 'code-assets.components.updateSettingModal.GroupDescription',
              defaultMessage: '分组描述',
            })}
            validator={this.checkPass2}
          >
            <Input.TextArea
              placeholder={intl.get({
                id: 'code-assets.src.utils.locale.EnterADescription',
                defaultMessage: '请输入描述',
              })}
              {...init('description')}
            />
          </FormItem>
          <FormItem
            label={
              <span>
                {intl.get({
                  id: 'code-assets.src.utils.locale.Openness',
                  defaultMessage: '公开性',
                })}
              </span>
            }
          >
            <Select
              showSearch
              placeholder={intl.get({
                id: 'code-assets.src.utils.locale.SelectPublicity',
                defaultMessage: '请选择公开性',
              })}
              {...init('visibility_level', {
                rules: [
                  {
                    required: true,
                    message: intl.get({
                      id: 'code-assets.src.utils.locale.SelectPublicity',
                      defaultMessage: '请选择公开性',
                    }),
                  },
                ],
                initValue: ENUM.visibility_level.PRIVATE,
              })}
              filterLocal
              dataSource={visibility_levels}
              style={{ width: '100%' }}
            />
          </FormItem>
          <FormItem label=" " className="tr">
            <Button type="primary" onClick={this.handleOk} loading={this.state.submitting}>
              {intl.get({
                id: 'code-assets.components.updateSettingModal.Save',
                defaultMessage: '保存',
              })}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  };

  renderAdvancedSetting = () => {
    return (
      <div className="setting-modal-tab-content">
        <div className="remove-wrapper">
          <div className="remove-wrapper-left">
            <div className="title">
              {intl.get({
                id: 'code-assets.components.updateSettingModal.RemoveGroupsAndRepositories',
                defaultMessage: '移除分组及仓库',
              })}
            </div>
            <div className="des">
              {intl.get({
                id: 'code-assets.components.updateSettingModal.RemoveTheGroupAndAll',
                defaultMessage: '移除分组及所有关联的资源，一旦操作无法恢复',
              })}
            </div>
          </div>
          <div className="remove-wrapper-right">
            <Button
              type="primary"
              warning
              className="remove-btn"
              onClick={this.remove}
              loading={this.state.isRemoveing}
            >
              {intl.get({
                id: 'code-assets.components.updateSettingModal.Remove',
                defaultMessage: '移除',
              })}
            </Button>
          </div>
        </div>
      </div>
    );
  };

  render() {
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={intl.get({
              id: 'code-assets.components.updateSettingModal.Set',
              defaultMessage: '设置',
            })}
            visible
            style={{ width: '800px', height: '450px' }}
            onOk={this.handleOk}
            onCancel={this.onClose}
            onClose={this.onClose}
            okProps={{ loading: !!this.state.submitting }}
            safeId="settingNode"
            footer={false}
          >
            <Tab tabPosition={'left'} shape="wrapped">
              <Tab.Item
                title={intl.get({
                  id: 'code-assets.components.updateSettingModal.BasicSettings',
                  defaultMessage: '基本设置',
                })}
                key="1"
              >
                {this.renderBasicSetting()}
              </Tab.Item>
              <Tab.Item
                title={intl.get({
                  id: 'code-assets.components.updateSettingModal.AdvancedSettings',
                  defaultMessage: '高级设置',
                })}
                key="2"
              >
                {this.renderAdvancedSetting()}
              </Tab.Item>
            </Tab>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
